<?php
/**
 * 题目链接 https://leetcode.cn/problems/plus-one/description/
 */

class Solution {

    /**
     * 从最后元素到前轮询+1
     * @param int[] $digits
     * @return int[]
     */
    public static function plusOne(array $digits): array 
    {
        $plus = 1;
        $len = count($digits);
        for ($i=$len - 1; $i >= 0; $i--) { 
            $last = $digits[$i] + $plus;
            if ($last == 10) {
                $digits[$i] = 0;
                $plus = 1;
                if ($i == 0) {
                    $digits = array_merge([1], $digits);
                }
            } else {
                $digits[$i] = $last;
                $plus = 0;
            }
        }
        
        return $digits;
    }

}

$test = [
    [[1,2,3]],
    [[4,3,2,1]],
    [[0]],
    [[9]],
    [[9,9]],
];
$result = [
    [1,2,4],
    [4,3,2,2],
    [1],
    [1,0],
    [1,0,0],
];

foreach ($test as $key => $value) {
    $r = Solution::plusOne($value[0]);
    if ($r !== $result[$key]) {
        echo sprintf("第%d个case不通过", $key) . PHP_EOL;
    }
    print_r($r);
}